package com.bestdreamer.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Semaphore 对并发访问的控制
 * 每秒放行 3 个线程
 * 释放多个许可
 */
@Slf4j
public class SemaphoreExample2 {

    private static final int threadCount = 200;

    public static void main(String[] args)throws Exception{
        ExecutorService exec = Executors.newCachedThreadPool();

        // 允许的并发数-3
        final Semaphore semaphore = new Semaphore(3);

        for(int i = 0; i < threadCount; i++){
            final int threadNum = i;
            exec.execute(() -> {
                try{
                    // 获取多个许可
                    semaphore.acquire(3);
                    test(threadNum);
                    // 释放多个许可
                    semaphore.release(3);
                }catch (Exception e){
                    log.error("exception",e);
                }
            });
        }
        exec.shutdown();
    }

    private static void test(int threadNum)throws Exception{
        log.info("{}",threadNum);
        Thread.sleep(1000);
    }

}
